#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Filename		:account.py
@Last modified	:2021/09/22 20:18:25
@Modified by	:eazhuhs
@Description	:账号相关功能：注册，登录，注销，短信等功能
'''
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from utils.tencent.sms import send_sms_single
import random
import json
import redis
from django.conf import settings
from web import models
from web.forms.account import RegisterModelForm, LoginModelForm, MobilePhoneSMSModelForm, LoginSMSModelForm
import datetime
import uuid
ORDER_NUMBER = 0
       
def register(request):
    if request.method=='GET':
        objs = RegisterModelForm(request)
        return render(request,'web/register.html',{'objs':objs})
    else:
        objs = RegisterModelForm(request, data=request.POST)
        ret = {'status':True,'msg':''}
        if objs.is_valid():
            # print(objs.cleaned_data)
            ret['status']=True
            # save data to UserInfo
            instance = objs.save()
            
            # 新注册也填写记录，为了区分不同阶段新注册用户
            price_free = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
            res = models.Transaction.objects.create(
                status = 2,
                user_id = instance.id,
                price_policy_id = price_free.id,
                count = 0,
                price = 0,
                start_datetime = datetime.datetime.now(),
                order = str(uuid.uuid4()) )
            
            # print(user_id)
            ret['msg'] = '/web/login' 
            return JsonResponse(ret)
            return render(request,'web/register.html', {'objs':objs,'ret':ret})
        else:
            ret['status']=False
            import json
            ret['msg'] = objs.errors
            v = json.dumps(ret)
            return HttpResponse(v)
            # return render(request,'app01/register.html', {'objs':objs,'ret':ret})
def index_login(request):
    return render(request,"web/index_login.html")
def index(request):
    return render(request,"web/index.html")
def send_sms(request):
    ret = {'status':False, 'error':''}
    objs = MobilePhoneSMSModelForm(request, data=request.GET)
    # print(objs)
    if objs.is_valid():
        ret['status'] = True
        if settings.TENCENT_SMS_DISABLE:    #腾讯云开通失败，用code代替
            from django_redis import get_redis_connection
            conn = get_redis_connection('default')
            value = conn.get(objs.cleaned_data['mobile_phone']) 
            # print(value)
            ret['error']=value.decode('utf-8')

        return JsonResponse(ret)
    ret['error']=objs.errors
    # import json
    # v = json.dumps(ret)
    # return HttpResponse(v)
    return JsonResponse(ret)

def send_sms_test(request):
    
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse("模板错误")
    code=random.randrange(1000,9999)
    res = send_sms_single('12811118888', template_id, [code,])
    # print(res)
    if res['result']==0:
        return HttpResponse("send_sms发送成功")
    else:
        return HttpResponse(res['errmsg'])

def send_sms_code(tpl, mobile_phone):
    ret = {'status':False, 'msg':''}
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)

    if not template_id:
        ret['msg'] = '模板错误'
    
    code=random.randrange(1000,9999)
    res = send_sms_single(mobile_phone, template_id, [code,])
    # print(res)
    if res['result']==0:
        ret={'status':True, 'msg':'send_sms_code发送成功'}
    else:
        ret={'status':False, 'msg':res['errmsg']}
    return ret 
def set_redis(value, ex):
    conn = redis.Redis(host='127.0.0.1',port=6379,password='abc',encoding='utf-8')
    conn.set('111',9999, ex=ex)
    value = conn.get('111')


def submit_code(request):
    if request.method=="GET":
        pass
    else:
        objs = RegisterModelForm(request.POST)
        objs.is_valid()
        ret = {'status':True, 'msg':''}
        if 'mobile_phone' in objs.cleaned_data.keys():
            mobile_phone=objs.cleaned_data['mobile_phone']
            # TODO
            # GET code by SMS
            # ret = send_sms_code('register',mobile_phone) 
            v = json.dumps(ret)
            return HttpResponse(v)

        else:
            ret['status']=False
            import json
            
            ret['msg'] = {'mobile_phone':objs.errors['mobile_phone']}
            v = json.dumps(ret)
            return HttpResponse(v)


def login_sms(request):
    if request.method =='GET':
        objs = LoginSMSModelForm(request.GET)
        return render(request,"web/login_sms.html",{'objs':objs})    
    else:
        objs = LoginSMSModelForm(request.POST)
        ret = {'status':False,'msg':''}
        # print(objs)
        if objs.is_valid():
            # print(objs.cleaned_data)
            userinfo = models.UserInfo.objects.filter(mobile_phone=objs.cleaned_data['mobile_phone']).first()
            request.session['id'] = userinfo.id
            request.session['username'] = userinfo.username
            request.session.set_expiry(60*30*24*12)
            ret['status']=True
            ret['msg']='/web/index_login'
            return JsonResponse(ret)    
        else:
            ret['status']=False
            import json
            ret['msg'] = objs.errors
            v = json.dumps(ret)
            return HttpResponse(v)
  
        
        
def login(request):
    ret = {'status':False, 'msg':''}
    if request.method=='GET':
        objs = LoginModelForm(request)
        # code = random.randrange(1000,9999)
        # request.session['code'] = code
        # request.session.set_expiry(600)
        ret['status']=True
        # ret['msg']=code
        return render(request,"web/login.html",{'objs':objs,'ret':ret})      
    else:
        objs = LoginModelForm(request, data=request.POST)
        ret = {'status':False,'msg':''}
        # print(objs)
        if objs.is_valid():
            from django.db.models import Q
            emailorphone = objs.cleaned_data['emailorphone']
            userinfo= models.UserInfo.objects.filter(Q(email=emailorphone) |  
                            Q(mobile_phone=emailorphone)).first()
            # userinfo = models.UserInfo.objects.filter(username=objs.cleaned_data['username']).first()
            request.session['id'] = userinfo.id
            request.session['username'] = userinfo.username
            request.session.set_expiry(60*30*24*12)
            # print(objs.cleaned_data)
            ret['status']=True
            ret['msg'] = '/web/index_login'
            return JsonResponse(ret)
        else:
            ret['status']=False
            ret['msg'] = objs.errors
            return JsonResponse(ret)

def logout(request):
    request.session.flush()
    return redirect('/web/login')


def image_code(request):
    # generate random code and image
    from utils.image_code import check_code
    image_obj, code = check_code()
    request.session['image_code'] = code
    request.session.set_expiry(600)

    # write image to memory
    from io import BytesIO
    stream = BytesIO()
    image_obj.save(stream, 'png')
    return HttpResponse(stream.getvalue())